package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.EmployeeMapper;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void saveOrUpdate(Employee entity) {
        if (entity.getPassword() != null) {
            Md5Hash hash = new Md5Hash(entity.getPassword(), entity.getUsername(), 2);
            entity.setPassword(hash.toString());
        }
        if (entity.getId() == null) {

            employeeMapper.insert(entity);
        } else {
            employeeMapper.deleteRelationWithRole(entity.getId());
            employeeMapper.updateByPrimaryKey(entity);
        }
        if (entity.getRoles() != null) {
            for (Role role : entity.getRoles()) {
                employeeMapper.buildRelationWithRole(entity.getId(), role.getId());
            }
        }
    }

    @Override
    public Employee selectByPrimaryKey(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> selectAll() {
        return employeeMapper.selectAll();
    }


    @Override
    public void changState(Long id) {
        employeeMapper.changState(id);
    }

    @Override
    public PageResult quey4List(EmployeeQueryObject qo) {
        Integer total = employeeMapper.query4Count(qo);
        if (total == 0) {
            return PageResult.PAGERESULT_EMPTY;
        }
        List<Employee> employees = employeeMapper.query4List(qo);
        return new PageResult(total, employeeMapper.query4List(qo));
    }

    @Override
    public void resetpassword(Employee entity) {
        Md5Hash hash = new Md5Hash(entity.getPassword(), entity.getUsername(), 2);
        entity.setPassword(hash.toString());
        employeeMapper.resetpassword(entity);
    }

    @Override
    public Employee getEmployeeByUsername(String username) {
        return employeeMapper.getEmployeeByUsername(username);
    }

    @Override
    public void importXls(MultipartFile file, HttpServletResponse response) throws Exception {
        InputStream inputStream = file.getInputStream();
        //创建Excel文件,指定输入流
        Workbook wb = new HSSFWorkbook(inputStream);
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++) {
            Employee employee = new Employee();
            Row row = sheet.getRow(i);
            employee.setUsername(row.getCell(0).getStringCellValue());
            employee.setRealname(row.getCell(1).getStringCellValue());
            employee.setPassword(row.getCell(2).getStringCellValue());
            employee.setTel(row.getCell(3).getStringCellValue());
            employee.setEmail(row.getCell(4).getStringCellValue());
            employeeMapper.insert(employee);
        }
    }

    /**
     * 根据条件查询员工列表导出到exl
     *
     * @param qo
     * @return
     */
    @Override
    public Workbook exportXls(EmployeeQueryObject qo) {
        //创建xls
        Workbook book = new HSSFWorkbook();
        //创建工作簿
        Sheet sheet = book.createSheet();
        //设置第一行的标题
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("真实姓名");
        row.createCell(2).setCellValue("联系方式");
        row.createCell(3).setCellValue("邮箱");
        row.createCell(4).setCellValue("所属部门");
        row.createCell(5).setCellValue("入职日期");
        row.createCell(6).setCellValue("状态");
        row.createCell(7).setCellValue("管理员");
        row.createCell(8).setCellValue("拥有的角色");

        List<?> list = employeeMapper.query4List(qo);

        for (int i = 0; i < list.size(); i++) {
            try {
                Employee emp = (Employee) list.get(i);
                //创建行
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(emp.getUsername());
                row.createCell(1).setCellValue(emp.getRealname());
                row.createCell(2).setCellValue(emp.getTel());
                row.createCell(3).setCellValue(emp.getEmail());
                row.createCell(4).setCellValue(emp.getDept() != null ? emp.getDept().getName() : "");
                row.createCell(5).setCellValue(emp.getHireDate());
                row.createCell(6).setCellValue(emp.getState() ? "在职" : "离职");
                row.createCell(7).setCellValue(emp.getAdmin());
                List<Role> roles = emp.getRoles();
                //如果角色不为空的话
                StringBuilder builder = new StringBuilder();
                if (roles != null) {
                    for (Role role : roles) {
                        String name = role.getName();
                        System.out.println(name);
                        builder.append(name);
                    }
                }
                row.createCell(8).setCellValue(builder.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return book;
    }

    //查询全部班主任
    @Override
    public List<Employee> selectAllClassManager() {
        return employeeMapper.selectAllClassManager();
    }

    //获取所有任课老师
    public List<Employee> selectAllTeacher() {
        return employeeMapper.selectAllTeacher();
    }

    //获取所有营销人员
    @Override
    public List<Employee> selectAllSalesman() {
        return employeeMapper.selectAllSalesman();
    }

    //获取所有收款人
    @Override
    public List<Employee> selectAllIncomMan() {
        return employeeMapper.selectAllIncomMan();
    }

    /**
     * 用户获取获取模板
     *
     * @return
     */
    public Workbook getImportXlsMode() {
        //创建xls
        Workbook book = new HSSFWorkbook();
        //创建工作簿
        Sheet sheet = book.createSheet();
        //设置第一行的标题
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("真实姓名");
        row.createCell(2).setCellValue("密码");
        row.createCell(3).setCellValue("联系方式");
        row.createCell(4).setCellValue("邮箱");
        /*row.createCell(5).setCellValue("所属部门");
        row.createCell(6).setCellValue("入职日期");
        row.createCell(7).setCellValue("状态");
        row.createCell(8).setCellValue("管理员");
        row.createCell(9).setCellValue("拥有的角色");*/
        return book;
    }

    /**
     * 通过角色的sn查询对应员工集合
     *
     * @param roleSn
     * @return员工对象集合
     */
    public List<Employee> selectEmpByRolesn(String roleSn) {
        return employeeMapper.selectEmpByRolesn(roleSn);
    }

    //记录用户当前的登陆时间
    public void markLoginDate(Employee employee) {
        employeeMapper.markLoginDate(employee);
    }

}
